<?php
/**
* @version $Id: mod_newsboxes.php 41 2008-07-29 07:03:32Z heriniaina.eugene $
* @package mod_newsboxes
* @copyright Copyright (C) 2006 serasera.org
* @comment This modules shows news boxes like in CNN.com
* URL : http://hery.blaogy.org/2007/03/22/joomla-newsbox-module/
*/

// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );

if(!defined('newsboxes_resize_image')) {
	define('newsboxes_resize_image', 1); //bcs in some server function_exists doesn't exist
	function newsboxes_resize_image($src_file, $dest_file, $new_size){
		$imagetype = array( 1 => 'GIF', 2 => 'JPG', 3 => 'PNG');
		$imginfo = getimagesize($src_file);
		if (!$imginfo) die("Image not found");
		$imginfo[2] = $imagetype[$imginfo[2]];
		if ($imginfo[2] != 'GIF' && $imginfo[2] != 'JPG' && $imginfo[2] != 'PNG')
		die(" File Type Not Supported! ");
		$srcWidth = $imginfo[0];
		$srcHeight = $imginfo[1];
		$ratio = $srcWidth / $new_size;
		$ratio = max($ratio, 1.0);
		$destWidth = $new_size;
		$destHeight = ($srcHeight / $ratio);
		if ($imginfo[2] == 'JPG') {
		$src_img = imagecreatefromjpeg($src_file);
		} else if ($imginfo[2] == 'PNG'){
		$src_img = imagecreatefrompng($src_file);
		} else if ($imginfo[2] == 'GIF') {
		$src_img = imagecreatefromgif($src_file);
		} else {
		return false;
		}
		$dst_img = imagecreatetruecolor($destWidth, $destHeight);
		//Added aplha-mode
		imagesavealpha($dst_img, true);
		$colour = imagecolorallocatealpha($dst_img, 0, 0, 0, 127);
    		imagefill($dst_img, 0, 0, $colour);
		//Added aplha-mode
		imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
		imagepng($dst_img, $dest_file);
		//imagejpeg($dst_img, $dest_file, '80');
		imagedestroy($src_img);
		imagedestroy($dst_img);
	}
}


$option = trim( mosGetParam( $_REQUEST, 'option', null ) );
$task = trim( mosGetParam( $_REQUEST, 'task', null ) );
$id = intval( mosGetParam( $_REQUEST, 'id', null ) );

global $mosConfig_cachepath, $_MAMBOTS, $nbx_duplicates;




$now 		= _CURRENT_SERVER_TIME;
$nullDate 	= $database->getNullDate();
$noauth 			= !$mainframe->getCfg( 'shownoauth' );
$nbx_sectionid =  intval($params->def('nbx_sectionid', 0));
$nbx_rows =  intval($params->def('nbx_rows', 2));
$nbx_columns =  intval($params->def('nbx_columns', 1));
$nbx_showtitles =  intval($params->def('nbx_showtitles', 1));
$nbx_showintro =  intval($params->def('nbx_showintro', 1));
$nbx_showdate =  intval($params->def('nbx_showdate', 0));
$nbx_introlength =  intval($params->def('nbx_introlength', 300));
$nbx_introformat =  $params->def('nbx_introformat', 'Text');
$nbx_readmore =  intval($params->def('nbx_readmore', 1));
$nbx_titlelink =  intval($params->def('nbx_titlelink', 1));
$nbx_showimage =  intval($params->def('nbx_showimage', 1));

//added in 1.1.0
$nbx_imgwidth = intval($params->def('nbx_imgwidth', 0));

$nbx_imageinside =  intval($params->def('nbx_imageinside', 1));
$nbx_ordering =  intval($params->def('nbx_ordering', 1));
$nbx_showcattitle =  intval($params->def('nbx_showcattitle', 0));
$nbx_showcatlink =  intval($params->def('nbx_showcatlink', 0));

$nbx_catid =  $params->def('nbx_catid', 0);

//added in 1.1.1
$nbx_noduplicate =  intval($params->def('nbx_noduplicate', 0));

//added in 1.1.3
$nbx_frontpageonly =  intval($params->def('nbx_frontpageonly', 0));

//for multiple categories
$nbx_cat_array = explode(",", $nbx_catid);

if($nbx_sectionid == 0 && $nbx_cat_array[0] == 0) {
	echo "This module is not yet configured... Please configure it or remove it.";
	return;
}

if(count($nbx_cat_array) >= 1) {

	for($ii=0; $ii<count($nbx_cat_array); $ii++) {
		//adding catid & sectionid thanx to greg
		//http://hery.blaogy.org/2007/03/22/joomla-newsbox-module/#comment-288
		$query = "SELECT a.id, a.introtext, a.images, a.fulltext, a.attribs, a.title, a.state, cc.title as cat_title, a.sectionid, a.catid, a.created "
		."\n FROM #__content AS a"
		."\n INNER JOIN #__categories AS cc ON cc.id = a.catid"
		."\n INNER JOIN #__sections AS s ON s.id = a.sectionid"
		. ($nbx_frontpageonly > 0 ? "\n INNER JOIN #__content_frontpage AS f ON f.content_id = a.id" : "" )
		."\n WHERE a.state = 1 "
		. (count($nbx_duplicates) > 0 ? " AND a.id NOT IN ('" . join("', '", $nbx_duplicates) . "') " : "" )
		."\n AND ( a.publish_up = " . $database->Quote( $nullDate ) . " OR a.publish_up <= " . $database->Quote( $now ) . " )"
		."\n AND ( a.publish_down = " . $database->Quote( $nullDate ) . " OR a.publish_down >= " . $database->Quote( $now ) . " )"
		. ( $noauth ? "\n AND a.access <= " . (int) $my->gid . " AND cc.access <= " . (int) $my->gid . " AND s.access <= " . (int) $my->gid : '' )
		. ($nbx_sectionid > 0  ? "\n AND a.sectionid = " . $nbx_sectionid : "")
		. (intval($nbx_cat_array[$ii]) > 0 ? " AND a.catid = " . $nbx_cat_array[$ii] : "" )
		. "\n AND cc.published = 1"
		."\n AND s.published = 1 ORDER BY "
		. ($nbx_ordering == 1 ? "\n a.ordering " : "\n a.created DESC " )
		;
		$database->setQuery( $query, 0, $nbx_rows );
		$nbxcats[] = $database->loadObjectList();
	}
}

$col = 0;
$col2 = 0;
$j = 0;

echo ($nbx_columns > 1 && count($nbxcats) > 1) ? "<table><tr><td valign=\"top\">" : "";

for($ii=0; $ii<count($nbxcats); $ii++) {
	$rows = $nbxcats[$ii];
		$col++;



		$nbx_last_cat = "";
		echo "<div class=\"" . $params->get( 'moduleclass_sfx') . "box\">";
		echo ($nbx_columns > 1 && count($nbxcats) <= 1) ? "<table><tr><td valign=\"top\">" : "";
		foreach($rows as $row) {

			//get itemid
			//simpler

			$Itemid = $mainframe->getItemid( $row->id, 0, 0);

			// no duplicate 
			//in 1.1.1
			if($nbx_noduplicate == 1) {
				$nbx_duplicates[] = $row->id;
			}

			//more complex
			/*
			$bs 	= $mainframe->getBlogSectionCount();
			$bc 	= $mainframe->getBlogCategoryCount();
			$gbs 	= $mainframe->getGlobalBlogSectionCount();

			$Itemid = $mainframe->getItemid( $row->id, 0, 0, $bs, $bc, $gbs );
			*/

			$row->Itemid_link = "&amp;Itemid=" . $Itemid ;

			$col2++;
			if($nbx_showcattitle > 0 && $row->cat_title != $nbx_last_cat) {
				echo "<div class=\"category\">" . ($nbx_showcatlink > 0 ? "<a href=\"" . sefRelToAbs('index.php?option=com_content&amp;task=category&amp;sectionid=' . $row->sectionid . '&amp;id=' . $row->catid . $row->Itemid_link) . "\">" : "") . $row->cat_title .  ($nbx_showcatlink > 0 ? "</a>" : "") . "</div>";
				$nbx_last_cat = $row->cat_title;
			}

			$imagetag = "";
			if($nbx_showimage > 0 && $row->images != "") {

				$img_str = $row->images;
				// split on \n the images fields into an array
				$img_str = explode( "\n", $row->images );

				$img = trim( $img_str[0] );

					// split on pipe the attributes of the image
				if ( $img ) {
					$attrib = explode( '|', trim( $img ) );
					// $attrib[0] image name and path from /images/stories

					// $attrib[1] alignment
					if ( !isset($attrib[1]) || !$attrib[1] ) {
						$attrib[1] = '';
					}

					// $attrib[2] alt & title
					if ( !isset($attrib[2]) || !$attrib[2] ) {
						$attrib[2] = 'Image';
					} else {
						$attrib[2] = htmlspecialchars( $attrib[2] );
					}

					//resize (added into 1.1.0 10/01/2008 13.03)
					$tmp_file_name = "";
					$imagefile = "";
					echo("<!-- debug " . $attrib[0] . " -->");
					if($nbx_imgwidth > 0) {
						//trying to create a thumbnail unik file for the image
						$tmp_file_name = md5($row->id . $nbx_imgwidth . $atrib[0] . filemtime($mosConfig_absolute_path .'/images/stories/'. $attrib[0])) . "." . substr(strrchr($mosConfig_absolute_path .'/images/stories/'. $attrib[0], '.'), 1);
						
						//mosConfig_absolute_path
						if(!file_exists($mosConfig_absolute_path . '/modules/mod_newsboxes/thumbs/' . $tmp_file_name)) {
							if(newsboxes_resize_image($mosConfig_absolute_path .'/images/stories/'. $attrib[0], $mosConfig_absolute_path . '/modules/mod_newsboxes/thumbs/' . $tmp_file_name, $nbx_imgwidth)) {
								$imagefile = $mosConfig_live_site .'/modules/mod_newsboxes/thumbs/' . $tmp_file_name;
								

							} else {
								$imagefile = $mosConfig_live_site .'/images/stories/'. $attrib[0] ;

							}
						} else {
							$imagefile = $mosConfig_live_site .'/modules/mod_newsboxes/thumbs/' . $tmp_file_name;
						}
						$size = ' width="' . $nbx_imgwidth . '" ';
					} else {
						$imagefile = $mosConfig_live_site .'/images/stories/'. $attrib[0] ;
						$size = '';
					}
					// assemble the <image> tag
					$imagetag = '<img src="'. $imagefile .'"'. $size;
					$imagetag .= ' hspace="6" alt="'. $attrib[2] .'" title="'. $attrib[2] .'" border="'. $border .'" style="float:'. $attrib[1] .'" />';

				}
			}


			$row->text = $row->introtext;

			$_MAMBOTS->loadBotGroup( 'content' );
			$results = $_MAMBOTS->trigger( 'onPrepareContent', array( &$row, &$params, '' ), true );

			echo "<div class=\"box " . ($j == 0 ? " first" : "") . " box_" . $j . "\">";
			if($nbx_imageinside == 0) {
				echo $imagetag;
			}


			if($nbx_showtitles != 0) {
				echo  "<div class=\"title\">" ;
				if($nbx_titlelink != 0) {
					echo "<a href=\"" . sefRelToAbs( 'index.php?option=com_content&amp;task=view&amp;id=' . $row->id . $row->Itemid_link ) . "\">";
				}
				echo $row->title ;
				if($nbx_titlelink != 0) {
					echo "</a>";
				}

				echo  "</div>" ;

			}
			if($nbx_showdate == 1) {

				echo "<div class=\"date\">" . mosFormatDate( $row->created, _DATE_FORMAT_LC ) . "</div>";
			}
			if($nbx_showintro != 0) {
				echo "<div class=\"text\">";

				if($nbx_imageinside == 1) {
					echo $imagetag;
				}

				if($nbx_introformat == 'Text') {
					if($nbx_introlength > 0) {
						if(strlen(strip_tags($row->text)) > $nbx_introlength) {
							$tmptext = substr(strip_tags($row->text), 0, $nbx_introlength);
							$pos = strrpos($tmptext, " ");
							if ($pos>0) {
							$tmptext = substr($tmptext, 0, $pos);
							}
							echo $tmptext . "...";
						} else {
							echo strip_tags($row->text);
						}
					} else {
						echo strip_tags($row->text);
					}
				} else {
					echo ampReplace( $row->text );
				}
				echo "</div>";
			}
			echo ($nbx_readmore != 0 ) ? "<div class=\"readmore\"><a href=\"" . sefRelToAbs( 'index.php?option=com_content&amp;task=view&amp;id=' . $row->id . $row->Itemid_link ) . "\" class=\"readon" . $params->get( 'moduleclass_sfx') . "\">" . _READ_MORE . "</a></div>": "";

			echo "</div>";

			echo (($nbx_columns > 1  && count($nbxcats) <= 1 ) && (floor($nbx_rows / $nbx_columns)  == $col2)) ? "</td><td valign=\"top\" class=\"hspacer\"></td><td valign=\"top\">" : "";

			$j++;

		}
		echo ($nbx_columns > 1 && count($nbxcats) <= 1) ? "</td></tr></table>" : "";

		echo "</div>";
		echo (($nbx_columns > 1  && count($nbxcats) > 1 ) && (floor(count($nbxcats) / $nbx_columns)  == $col)) ? "</td><td valign=\"top\">" : "";

}



echo ($nbx_columns > 1  && count($nbxcats) > 1) ? "</td></tr></table>" : "";




?>